import { Injectable } from '@nestjs/common';
import { DiaryCreateDao, DiaryFindDao, DiaryUpdateDao, DiaryBillCreateDao, DiaryBillUpdateDao, BindBillDao } from './interfaces/diary.interface';
import { InjectRepository } from '@nestjs/typeorm';
import { Diary, DiaryBill } from './diary.entity';
import { Repository } from 'typeorm';

@Injectable()
export class DiaryService {
  constructor(
    @InjectRepository(Diary)
    private diaryRepository: Repository<Diary>,
    @InjectRepository(DiaryBill)
    private diaryBillRepository: Repository<DiaryBill>,
  ) { }

  createBill(diaryBill: DiaryBillCreateDao) {
    return this.diaryBillRepository.save(diaryBill);
  }

  create(diary: DiaryCreateDao) {
    return this.diaryRepository.save(diary);
  }

  find(diary: DiaryFindDao) {
    return this.diaryRepository.find({ where: { userid: diary.userid, diaryid: diary.diaryid } });
  }

  update(diary: DiaryUpdateDao) {
    return this.diaryRepository.update({ userid: diary.userid, diaryid: diary.diaryid }, { content: diary.content })
      .then(() => this.diaryRepository.findOne({ where: { userid: diary.userid, diaryid: diary.diaryid } }));
  }

  updateBill(diaryBill: DiaryBillUpdateDao) {
    return this.diaryBillRepository.update({ userid: diaryBill.userid, diarybillid: diaryBill.diarybillid }, { desc: diaryBill.desc, title: diaryBill.title })
      .then(() => this.diaryBillRepository.findOne({ where: { userid: diaryBill.userid, diarybillid: diaryBill.diarybillid } }));
  }

  bindBill(bindBill: BindBillDao) {
    return this.diaryBillRepository.update({ userid: bindBill.userid, diarybillid: bindBill.diarybillid }, { bindbill: bindBill.bindbill })
    .then(() => this.diaryBillRepository.update({ diarybillid: bindBill.bindbill }, { bindbill: bindBill.diarybillid }))
    .then(() => this.diaryBillRepository.findOne({ where: { userid: bindBill.userid, diarybillid: bindBill.diarybillid } }));
  }

}